package com.ibl.rover.lite.client.Activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.w3c.dom.ls.LSInput;

import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Application.OrderBookingLine;
import com.ibl.rover.lite.client.constants.RoverConstants;
import com.ibl.rover.lite.common.bean.CustomerBean;
import com.ibl.rover.lite.common.bean.OrderBean;
import com.ibl.rover.lite.common.bean.ProductBean;
import com.ibl.rover.lite.common.bean.ProductOrderBean;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.Criteria.Operators;
import com.ibl.rover.lite.common.db.DatabaseManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;

public class OrderReportActivity extends Activity implements OnClickListener {

	private Logger logger = new Logger();
	private ApplicationContext roverApp;
	private DatabaseManager manager = null;
	private Spinner dateSpinner = null;
	private DatePickerDialog.OnDateSetListener toDateSetListener;
	private String toDate;
	private Button btnToDate;
	private Calendar calender;
	private List<OrderBean> orderList;
	private View view;
	private TextView orderAmount;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.order_rerport);
			initialize();
		} catch (Exception e) {
			logger.logException("onCreate Exception ", e);
		}
	}

	private void initialize() {
		try {

			roverApp = (ApplicationContext) getApplication();
			manager = roverApp.getDatabaseManager();

			calender = Calendar.getInstance();
			// Date Dialogs Set Listener
			toDateSetListener = new DatePickerDialog.OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker view, int year,
						int monthOfYear, int dayOfMonth) {
					StringBuilder text = new StringBuilder();
					btnToDate.setText(text.append(dayOfMonth).append("/")
							.append(monthOfYear + 1).append("/").append(year)
							.toString());
					toDate = btnToDate.getText().toString();
				}
			};

			dateSpinner = (Spinner) findViewById(R.id.sales_type_spinner);

			ArrayAdapter<CharSequence> dateAdapter = new ArrayAdapter<CharSequence>(
					this, android.R.layout.simple_spinner_item,
					getOrderDistinctDate());
			dateAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			dateSpinner.setAdapter(dateAdapter);

			getOrders();

			// btnToDate.setOnClickListener(this);
			((Button) findViewById(R.id.search_report_order))
					.setOnClickListener(this);

		} catch (Exception e) {
			logger.logException("initialize Exception", e);

		}

	}

	private void getOrders() {
		try {
			orderList = manager.findAllBean(OrderBean.class);
			setTitle("Orders (" + orderList.size() + ")");
			buildOrderReport();
		} catch (Exception e) {
			logger.logException("getOrders Exception", e);
		}

	}

	private void buildOrderReport() {
		try {
			TableLayout retailersTablereouteCustromerTable = (TableLayout) findViewById(R.id.report_order_table);
			int textColor = getResources().getColor(
					R.color.table_item_text_color);
			retailersTablereouteCustromerTable
					.setVisibility(TableLayout.VISIBLE);
			if (retailersTablereouteCustromerTable.getChildCount() > 1) {
				retailersTablereouteCustromerTable.removeViews(1,
						retailersTablereouteCustromerTable.getChildCount() - 1);
			}
			LayoutParams otherParams = new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

			otherParams.setMargins(1, 0, 0, 1);
			double orderAmount = 0.0;
			for (OrderBean orderBean : orderList) {
				TableRow row = new TableRow(this);
				row.setTag(orderBean);

				TextView txtOrderId = new TextView(this);
				txtOrderId.setTextAppearance(this, R.style.table_item_font);
				txtOrderId.setText(orderBean.getOrderId());
				txtOrderId.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtOrderId.setPadding(5, 0, 5, 0);
				txtOrderId.setTextColor(textColor);

				row.addView(txtOrderId, otherParams);

				TextView txtOrderAmount = new TextView(this);
				txtOrderAmount.setTextAppearance(this, R.style.table_item_font);
				txtOrderAmount.setText(orderBean.getAmount());
				txtOrderAmount.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtOrderAmount.setPadding(5, 0, 5, 0);
				txtOrderAmount.setTextColor(textColor);

				row.addView(txtOrderAmount, otherParams);
				if (orderBean.getStatus().equals("Active"))
					orderAmount += Double.parseDouble(orderBean.getAmount());

				TextView txtOrderStatus = new TextView(this);
				txtOrderStatus.setTextAppearance(this, R.style.table_item_font);
				txtOrderStatus.setText(orderBean.getStatus());
				txtOrderStatus.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtOrderStatus.setPadding(5, 0, 5, 0);
				txtOrderStatus.setTextColor(textColor);
				txtOrderStatus.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View view) {
						statusUpdateOrder(view);
					}
				});
				row.addView(txtOrderStatus, otherParams);

				TextView txtOrderSalesType = new TextView(this);
				txtOrderSalesType.setTextAppearance(this,
						R.style.table_item_font);
				txtOrderSalesType.setText(orderBean.getSalesType());
				txtOrderSalesType.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtOrderSalesType.setPadding(5, 0, 5, 0);
				txtOrderSalesType.setTextColor(textColor);

				row.addView(txtOrderSalesType, otherParams);

				CheckBox actionButtion = new CheckBox(this);

				actionButtion.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				actionButtion.setPadding(2, 0, 2, 0);
				actionButtion.setButtonDrawable(R.drawable.details);
				actionButtion.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View view) {

						TableRow row = (TableRow) view.getParent();
						OrderBean orderBean = (OrderBean) row.getTag();
						getOrderSumamry(orderBean);

					}
				});

				row.addView(actionButtion, otherParams);
				retailersTablereouteCustromerTable.addView(row);
				retailersTablereouteCustromerTable.invalidate();
			}

			((TextView) findViewById(R.id.lbl_total_amount))
					.setText("Total Amount :" + orderAmount);

		} catch (Exception e) {
			logger.logException("build Order Report Excepttion ", e);
		}

	}

	private void statusUpdateOrder(View view) {
		try {

			TextView textView = (TextView) view;
			final TableRow row = (TableRow) textView.getParent();
			this.view = view;
			this.orderAmount = ((TextView) OrderReportActivity.this
					.findViewById(R.id.lbl_total_amount));
			OrderBean orderBean = (OrderBean) row.getTag();
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			if (orderBean.getStatus().equals("Active")) {

				builder.setMessage(
						getResources().getString(
								R.string.mark_as_retailer_inactive))
						.setCancelable(false)
						.setPositiveButton(
								getResources().getString(R.string.common_yes),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										((TextView) OrderReportActivity.this.view)
												.setText("Cancel");
										OrderBean bean = (OrderBean) row
												.getTag();
										bean.setStatus("Cancel");
										manager.updateBean(bean);
										// Double
										// orderAmount=Double.valueOf(((TextView)OrderReportActivity.this.findViewById(R.id.lbl_total_amount)).getText().toString());
										String orderAmt = OrderReportActivity.this.orderAmount
												.getText().toString();
										String[] orderprice = orderAmt
												.split(":");
										Double orderAmount = Double
												.valueOf(orderprice[1]);
										orderAmount -= Double.parseDouble(bean
												.getAmount());
										((TextView) OrderReportActivity.this
												.findViewById(R.id.lbl_total_amount)).setText("Total Amount:"
												+ String.valueOf(orderAmount));

									}
								})
						.setNegativeButton(
								getResources().getString(R.string.common_no),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});
			} else {
				builder.setMessage(
						getResources().getString(
								R.string.mark_as_retailer_active))
						.setCancelable(false)
						.setPositiveButton(
								getResources().getString(R.string.common_yes),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										((TextView) OrderReportActivity.this.view)
												.setText("Active");
										OrderBean bean = (OrderBean) row
												.getTag();
										bean.setStatus("Active");
										manager.updateBean(bean);
										String orderAmt = OrderReportActivity.this.orderAmount
												.getText().toString();
										String[] orderprice = orderAmt
												.split(":");
										Double orderAmount = Double
												.valueOf(orderprice[1]);
										orderAmount += Double.parseDouble(bean
												.getAmount());
										((TextView) OrderReportActivity.this
												.findViewById(R.id.lbl_total_amount)).setText("Total Amount:"
												+ String.valueOf(orderAmount));
									}
								})
						.setNegativeButton(
								getResources().getString(R.string.common_no),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});

			}
			builder.setTitle(R.string.common_alert);
			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			logger.logException("statusUpdateOrder Excepotion", e);
		}

	}

	/**
	 * Get Order DEtial
	 */
	private void getOrderSumamry(OrderBean orderBean) {
		try {

			Criteria<CustomerBean> criteria = manager
					.generateCriteria(CustomerBean.class);
			criteria.addRestriction(CustomerBean.COL_CODE, Operators.isEqual,
					orderBean.getCustomerCode());

			List<CustomerBean> list = criteria.execute();
			if (list.size() > 0) {
				roverApp.getViewContext().put(RoverConstants.CURRENT_CUSTOMER,
						list.get(0));
				roverApp.getViewContext()
						.put(RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS,
								orderBean);

				Intent intent = new Intent(OrderReportActivity.this,
						OrderSummaryActivity.class);
				startActivity(intent);

			}

		} catch (Exception e) {
			logger.logException("get Order Detail", e);
		}

	}

	//
	// private OrderBookingLine getProductBeanList(OrderBean orderBean) {
	// try {
	// Criteria<ProductOrderBean> criteria = manager
	// .generateCriteria(ProductOrderBean.class);
	// criteria.addRestriction(ProductOrderBean.COL_ORDER_KEY,
	// Operators.isEqual, orderBean.getOrderId());
	//
	// List<ProductOrderBean> list = criteria.execute();
	// List<ProductBean> productBeans = new ArrayList<ProductBean>();
	// List<String> quantityList = new ArrayList<String>();
	// ProductOrderBean productOrderBean;
	// if (list.size() > 0) {
	//
	// Criteria<ProductBean> criteria2 = manager
	// .generateCriteria(ProductBean.class);
	// productOrderBean = list.get(0);
	// criteria2.addRestriction(ProductBean.COL_PRODUCT_CODE,
	// Operators.isEqual, productOrderBean.getProductCode());
	// quantityList.add(productOrderBean.getQuantity());
	// for (int i = 1; i < list.size(); i++) {
	//
	// productOrderBean = list.get(i);
	// criteria2.addRestriction(
	// ProductBean.COL_PRODUCT_CODE, Operators.isEqual,
	// productOrderBean.getProductCode());
	// quantityList.add(productOrderBean.getQuantity());
	// }
	// productBeans = criteria2.execute();
	// OrderBookingLine orderBookingLine = new OrderBookingLine();
	// orderBookingLine.setOrderAmount(orderBean.getAmount());
	// orderBookingLine.setProductBeanList(productBeans);
	// orderBookingLine.setProductQuantitylist(quantityList);
	// return orderBookingLine;
	// }
	//
	// } catch (Exception e) {
	// logger.logException("getproductBeanList", e);
	// }
	// return null;
	// }

	// private List<String> getProductQuantityList(List<ProductBean>
	// productBeanList) {
	// try {
	// List<String> quantitylist=new ArrayList<String>();
	// for (ProductBean productBean : productBeanList) {
	// quantitylist.add(produc)
	// }
	//
	//
	//
	// } catch (Exception e) {
	// logger.logException("getProductQuantityList	", e);
	// }
	// }

	@Override
	protected Dialog onCreateDialog(int id) {
		try {
			logger.log("[InventoryReport ] onCreateDialog START");

			return new DatePickerDialog(this, toDateSetListener,
					calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
					calender.get(Calendar.DAY_OF_MONTH));

		} catch (Exception e) {
			logger.logException("[ InventoryReport ] onCreateDialog ", e);
			return null;
		}

	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {

		case R.id.search_report_order:
			searchOrder();
			break;

		default:
			break;
		}

	}

	private void searchOrder() {
		try {
			Criteria<OrderBean> criteria = manager
					.generateCriteria(OrderBean.class);
			criteria.addRestriction(OrderBean.COL_DATE, Operators.isEqual,
					dateSpinner.getSelectedItem().toString());
			orderList = criteria.execute();
			setTitle("Orders (" + orderList.size() + ")");
			buildOrderReport();
		} catch (Exception e) {
			logger.logException("search Order", e);
		}
	}

	/**
	 * Get Distinct Date
	 */
	private String[] getOrderDistinctDate() {
		try {
			Cursor cursor = manager.executeSQL(
					"select DISTINCT DATE FROM ORDER_BEAN", null);
			cursor.moveToFirst();
			String[] orderDate = new String[cursor.getCount()];
			int i = 0;
			while (!cursor.isAfterLast()) {
				orderDate[i++] = cursor.getString(0);
				cursor.moveToNext();
			}
			return orderDate;
		} catch (Exception e) {
			logger.logException("get Order Distict Date", e);
		}
		return null;
	}
}
